class AccountsController < ApplicationController
  before_action :check_account_role
  before_action :set_account, only: [:show, :edit, :update, :destroy, :blocked, :toggle_admin]

  # GET /accounts
  def index
    @accounts = Account.all
  end

  # GET /accounts/1
  def show
  end

  # GET /accounts/1/edit
  def edit
  end

  # PATCH/PUT /accounts/1
  def update
    respond_to do |format|
      if @account.update(account_params)
        format.html { redirect_to @account, notice: 'Account was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @account.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /accounts/1
  def destroy
    @account.destroy
    respond_to do |format|
      format.html { redirect_to accounts_url }
      format.json { head :no_content }
    end
  end

  def blocked
    @account.toggle!(:blocked)
    respond_to do |format|
      format.js
    end
  end

  def toggle_admin
    toggle_role = @account.act_as_admin? ? 'user' : 'admin'
    respond_to do |format|
      if @account.update_attribute(:role, toggle_role)
        format.js
      else
        format.js { render :json => {:error => 'toggle admin failed'}, :status => :unprocessable_entity } 
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_account
      @account = Account.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def account_params
      params.require(:account).permit(:username, :email, :role)
    end

    def check_account_role
      unless current_account.can_manager_site?
        redirect_to root_path, notice: "you hava no authority to manage site"
      end
    end
end
